package agents.profileragentbehaviuors;

import java.io.IOException;

import resource.UserProfile;
import gui.TourGUI;
import agents.CuratorAgent;
import agents.ProfilerAgent;
import jade.core.behaviours.OneShotBehaviour;
import jade.core.behaviours.SequentialBehaviour;
import jade.core.behaviours.SimpleBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;

public class WalkTourBehaviour extends SequentialBehaviour {
	private String[] tour;
	private String[] detailedArtifactInfo;
	private ProfilerAgent agent;

	public WalkTourBehaviour(ProfilerAgent agent){
		super(agent);
		detailedArtifactInfo = null;
		this.agent = agent;
		this.addSubBehaviour(new SendGetDetailedInfoRequestBehaviour());
		this.addSubBehaviour(new ReceiveDetailedInfoBehaviour());
		this.addSubBehaviour(new ShowTourBehaviour());
	}
	
	
	private class SendGetDetailedInfoRequestBehaviour extends OneShotBehaviour {
		@Override
		public void action() {
			tour = agent.getTour();
			DFAgentDescription dfd = new DFAgentDescription();
			ServiceDescription sd = new ServiceDescription();
			sd.setType("getDetailedInformationAboutArtifactWithName");
			dfd.addServices(sd);
			try {
				DFAgentDescription[] dfds = DFService.search(myAgent, dfd);
				if (dfds.length > 0) {
					ACLMessage msg = new ACLMessage(CuratorAgent.GET_INFO_SERVICE);
					msg.addReceiver(dfds[0].getName());
					msg.setSender(myAgent.getAID());
					msg.setContentObject(tour);
					myAgent.send(msg);
				} 
			} catch (FIPAException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private class ReceiveDetailedInfoBehaviour extends SimpleBehaviour {
		private boolean done = false;
		@Override
		public void action() {
			ACLMessage msg = myAgent.receive();
			if(msg != null){
				try {
					detailedArtifactInfo = (String[]) msg.getContentObject();
					done = true;
				} catch (UnreadableException e) {
					e.printStackTrace();
				}
			}
			else{
				block();
			}		
		}
		
		@Override
		public boolean done() {
			return done;
		}
	}
	
	private class ShowTourBehaviour extends OneShotBehaviour {
		@Override
		public void action() {
			UserProfile user = agent.getUserInfo();
			for (int i = 0; i < tour.length; i++){
				user.addVisitedArtifact(tour[i]);
			}
			
			TourGUI tourGui = new TourGUI(tour, detailedArtifactInfo, "Tour");
			tourGui.setVisible(true);
		}
	}
}
